import logging
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
import time
from conf import settings
from db.excel_handler import read
from db.models import Host
from interface import init_interface, login_interface, connect_interface, auth_interface
from interface.auth_interface import no_such_role_exist
from interface.init_interface import config_dict
from lib.common import wait_table, wait_list, host_row_search, return_page

logging.config.dictConfig(settings.LOGGING_DIC)  # 导入上面定义的logging配置
logger = logging.getLogger("TEST")

# 初始化
host_list = []
browser, wait = (None, None)
init_sum = 0

def init():
    global host_list, browser, wait
    init_interface.init_settings()
    host_list = init_interface.host_init_interface()
    browser, wait = init_interface.browser_init_interface()
    login_interface.login_interface(browser, wait)


def test(id, host):
    """
    4A登录
    """
    # # 登录 进入设备管理
    # login_interface.login_interface(browser, wait)
    global init_sum
    # 搜索 选择主机

    print(f'--------第{id}台主机 {host.ip}---已经初始化数量:{init_sum}')
    host_row = host_row_search(browser, host)
    if host_row is None:
        print('未搜索到主机')
        host.os_release = '未搜索到主机'
        host.save(id)
        return
    host_row.click()

    # browser.execute_script("arguments[0].click();", host_row)

    # # 测试连接
    # browser.find_element(By.XPATH, '//*[@id="testConnection"]').click()
    #
    # browser.switch_to.frame(1)
    #
    # browser.find_element(By.XPATH, '//*[@id="id0"]').click()
    #
    # text = wait.until(EC.presence_of_element_located((
    #     By.XPATH, '//*[@id="dialog-message"]'
    # ))).text
    # print(text)
    # browser.switch_to.parent_frame()
    # browser.find_element(By.XPATH, '/html/body/div[6]/div[1]/a/span').click()

    # 初始化
    initializing_status = config_dict.get('ALLOWS_INIT_STATUS')
    browser.find_element(By.XPATH, '//*[@id="init"]').click()
    time.sleep(0.2)
    try:
        browser.find_element(By.XPATH, f'/html/body/div[{6 + init_sum}]/div[11]/button[2]/span').click()
        # wait.until(EC.presence_of_element_located((
        #     By.XPATH, f'/html/body/div[{6 + init_sum}]/div[11]/button[2]/span'
        # ))).click()
        init_sum += 1
    except Exception as e:
        print(e)
        print("已初始化")
        logger.info("已初始化或无法初始化")
        host.sync_status = '已初始化'
        host.save(id)
        return
    # 稍后查看
    browser.switch_to.frame(1)
    browser.find_element(By.XPATH, '//*[@id="initButton"]').click()
    browser.switch_to.parent_frame()
    print("自动初始化")
    host.sync_status = '自动初始化'
    host.save(id)
    wait_table(browser)

    # 手工同步
    # browser.find_element(By.XPATH, '//*[@id="manualSync"]').click()
    #
    # for i in range(6, 1000):
    #     if browser.find_element(By.XPATH, f'/html/body/div[{i}]').is_displayed():
    #         browser.find_element(By.XPATH, f'/html/body/div[{i}]/div[11]/button[2]/span').click()
    #         browser.switch_to.frame(1)
    #         #  time.sleep(3)
    #         for t in range(1000):
    #             time.sleep(0.2)
    #             text = wait.until(EC.presence_of_element_located((
    #                 By.XPATH, '/html/body/div[1]/div/div/div/div'
    #             ))).text
    #             if "手工同步" in text:
    #                 print(text)
    #                 break
    #
    #         browser.switch_to.parent_frame()
    #         browser.find_element(By.XPATH, f'/html/body/div[{i + 1}]/div[1]/a').click()
    #         break

    # # 从账号查询
    # browser.find_element(By.XPATH, '//*[@id="viewAcct"]').click()
    #
    # wait_table(browser)
    #
    # browser.find_element(By.XPATH, '//*[@id="acctName"]').send_keys(host.account)
    # browser.find_element(By.XPATH, '//*[@id="searchButton"]').click()
    #
    # wait_table(browser)
    #
    # text_list = []
    # for i in range(1, 150):
    #     try:
    #         text_list.clear()
    #         account_row = browser.find_element(
    #             By.XPATH, f'/html/body/div[1]/div/div/span[1]/div/div/div/div/div[3]/div[3]/div/table/tbody/tr[{i}]'
    #         )
    #         for text in account_row.text.split(" "):
    #             text_list.append(text)
    #
    #         print(i, text_list)
    #         if text_list[0] == host.account:
    #             print("查询到该用户")
    #             break
    #
    #     except NoSuchElementException as e:
    #         if i == 11:
    #             print("此页可能没有该主机NoSuchElement")
    #         else:
    #             print("查询结束，此页可能没有该主机")
    #         break

    # # 角色授权
    # # 设备批量授权
    # browser.find_element(By.XPATH, '//*[@id="sysrolemng"]').click()
    # # 键入功能验证
    # browser.find_element(By.XPATH, '//*[@id="roleName"]').send_keys(host.role)
    #
    # wait_table(browser)
    # # 查询
    # browser.find_element(By.XPATH, '/html/body/div[1]/div/div/div[2]/div/table/tbody/tr[2]/td[5]/div/table').click()
    #
    # wait_table(browser)
    #
    # # 选中
    # text_list = []
    # try:
    #     for i in range(1, 150):
    #         text_list.clear()
    #         role_row = browser.find_element(
    #             By.XPATH, f'/html/body/div[1]/div/div/div[4]/div[3]/div[3]/div/table/tbody/tr[{i}]'
    #         )
    #         for text in role_row.text.split(" "):
    #             text_list.append(text)
    #
    #         print(i, text_list)
    #
    #         if text_list[1] == host.role:  # 如果角色存在
    #             print(text_list[1])
    #             role_row.click()
    #             break
    # except NoSuchElementException as e:
    #     if i == 11:
    #         host.account_status = "此页可能没有该角色NoSuchElement"
    #         host.is_bad = True
    #         print("查询结束，此页可能没有此角色")
    #         return
    #     else:
    #         host.account_status = "没有此角色NoSuchElement"
    #         host.is_bad = True
    #         print("查询结束，没有此用户")
    #         return
    # # 编辑
    # browser.find_element(By.XPATH, '/html/body/div[1]/div/div/div[3]/div/div[2]/table').click()
    #
    # # 切换iframe
    # browser.switch_to.parent_frame()
    # browser.switch_to.frame(4)
    #
    # # 等待加载
    # wait_list(browser)
    #
    # # 输入ip 输入从账号 查询
    # browser.find_element(By.XPATH, '//*[@id="unentityIp"]').send_keys(host.ip)
    # browser.find_element(By.XPATH, '//*[@id="unacctName"]').send_keys(host.account)
    # # 查询
    # browser.find_element(By.XPATH,
    #                      '/html/body/div[1]/div/div/div/div/table[2]/tbody/tr/td[1]/fieldset/table/tbody/tr[2]/td[3]/div/table/tbody/tr/td[2]').click()
    # # 等待加载
    # wait_list(browser)
    #
    # text_list = []
    # for i in range(1, 150):
    #     # try:
    #     text_list.clear()
    #     host_account_row = browser.find_element(
    #         By.XPATH,
    #         f'/html/body/div[1]/div/div/div/div/table[2]/tbody/tr/td[1]\
    #         /fieldset/table/tbody/tr[3]/td/div/div[3]/div[3]/div/table/tbody/tr[{i}]'
    #     )
    #     for text in host_account_row.text.split(" "):
    #         text_list.append(text)
    #
    #     print("主机", i, text_list)
    #     if text_list[2] == host.ip and text_list[1] == '主机':
    #         print("查询到该主机")
    #         # 点开账号列表
    #         browser.find_element(
    #             By.XPATH,
    #             f'/html/body/div[1]/div/div/div/div/table[2]/tbody/tr/td[1]\
    #             /fieldset/table/tbody/tr[3]/td/div/div[3]/div[3]/div/table/tbody/tr/td[{i}]/a'
    #         ).click()
    #
    #         time.sleep(0.2)
    #
    #         account_list = []
    #
    #         for t in range(1, 150):
    #             account_row = browser.find_element(
    #                 By.XPATH,
    #                 f'/html/body/div[1]/div/div/div/div/table[2]/tbody/tr/td[1]/fieldset/table/tbody/tr[3]/td/div/div[3]/div[3]/div/table/tbody/tr[{i}]/td[2]/div/div/div[3]/div[3]/div/table/tbody/tr[{t}]'
    #             )
    #             for text in account_row.text.split(" "):
    #                 account_list.append(text)
    #
    #             print("账号", t, account_list)
    #             if account_list[0] == host.account:
    #                 print("查询到该用户")
    #                 # 选中
    #                 browser.find_element(
    #                     By.XPATH,
    #                     f'/html/body/div[1]/div/div/div/div/table[2]/tbody/tr/td[1]/\
    #                     fieldset/table/tbody/tr[3]/td/div/div[3]/div[3]/div/table/tbody/tr[{i + 1}]\
    #                     /td[2]/div/div/div[3]/div[3]/div/table/tbody/tr[{t}]/td[1]/input'
    #                 )
    #
    #         break

    # except NoSuchElementException as e:
    #     if i == 11:
    #         print("此页可能没有该主机NoSuchElement")
    #     else:
    #         print("查询结束，此页可能没有该主机")
    #     break

    # l = browser.find_element(By.XPATH, ' //*[@id="1"]').text.split(" ")
    # print(l)


def run():
    # host = Host(ip="10.72.200.227", account="root")
    # host = Host(ip="10.179.16.207", account="rpcuser", role="功能验证")
    # login(host)

    init()

    id = 0
    while True:
        if id >= len(host_list):
            return
        test(id + 1, host_list[id])
        id += 1


if __name__ == '__main__':
    pass
    run()
    # time.sleep(5)
